package de.slothsoft.wasbinich.core.database.webservice;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import de.slothsoft.wasbinich.core.FullPicture;
import de.slothsoft.wasbinich.core.WebserviceUrls;
import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.ManagerBean;

public class WebserviceManagerBean extends AbstractWebserviceBean implements ManagerBean {

    private static final Type PICTURE_LIST_TYPE = new TypeToken<ArrayList<FullPicture>>() {
    }.getType();

    public WebserviceManagerBean(RestCommunicator communicator) {
	super(communicator);
	setSendAccessToken(true);
    }

    @Override
    public List<FullPicture> getPictures() throws DatabaseException {
	String json = post(WebserviceUrls.getManagerPicturesUrl());
	return getPicturesFromString(json);
    }

    @Override
    public FullPicture getPicture(long id) throws DatabaseException {
	String json = post(WebserviceUrls.getManagerPictureByIdUrl(id));
	return getPictureFromString(json);
    }

    @Override
    public FullPicture updatePicture(FullPicture picture) throws DatabaseException {
	String json = post(WebserviceUrls.getManagerPictureUpdateUrl(), GSON.toJson(picture));
	return getPictureFromString(json);
    }

    @Override
    public FullPicture createPicture(FullPicture picture) throws DatabaseException {
	String json = post(WebserviceUrls.getManagerPictureCreateUrl(), GSON.toJson(prepareForUpload(picture)));
	return getPictureFromString(json);
    }

    protected FullPicture prepareForUpload(FullPicture picture) throws DatabaseException {
	return picture;
    }

    @Override
    public void deletePicture(long id) throws DatabaseException {
	post(WebserviceUrls.getManagerPictureDeleteUrl(id));
    }

    protected static List<FullPicture> getPicturesFromString(String json) throws DatabaseException {
	try {
	    List<FullPicture> result = GSON.fromJson(json, PICTURE_LIST_TYPE);
	    if (result == null) {
		result = new ArrayList<FullPicture>();
	    }
	    return result;
	} catch (JsonSyntaxException e) {
	    System.err.println("Error in WebserviceManagerBean.getPicturesFromString(): " + json); //$NON-NLS-1$
	    throw e;
	}
    }

    protected static FullPicture getPictureFromString(String json) throws DatabaseException {
	try {
	    return GSON.fromJson(json, FullPicture.class);
	} catch (JsonSyntaxException e) {
	    System.err.println("Error in WebserviceManagerBean.getPictureFromString(): " + json); //$NON-NLS-1$
	    throw e;
	}
    }

}
